# coding:utf-8

import datetime
from numpy.ma import array
from src.util.picture_util import PictureUtil
from src.manager.oracle_manager import OracleManager
from src.manager.log_manager import LogManager
from src.config.oracle_config import OracleConfig
from src.config.stock_week_config import StockWeekConfig

Logger = LogManager.get_logger(__name__)


class StockWeekHandler:

    def __init__(self) -> None:
        """
        构造函数，初始化oracle_manager和cursor对象
        """
        self.oracle_manager = OracleManager(OracleConfig.Username, OracleConfig.Password, OracleConfig.Url)
        self.oracle_manager.connect()
        self.cursor = self.oracle_manager.get_cursor()

    def paint_stock_week_avg_kd_and_macd_gold_cross_profit_rate_scatter(self):
        """
        生成macd金叉交易（开始时间）的收益率和周线级别平均KD值之间关系的散点图
        """
        Logger.info("生成macd金叉交易（开始时间）的收益率和周线级别平均KD值之间关系的散点图")

        self.cursor.execute(
            "select * from mdl_macd_gold_cross t "
            "where t.buy_date between to_date('" + StockWeekConfig.Mdl_Macd_Gold_Cross_Begin_Date + "','yyyy-mm-dd') "
                                                                                                    "and to_date('" + StockWeekConfig.Mdl_Macd_Gold_Cross_End_Date + "','yyyy-mm-dd')")
        mdl_macd_gold_cross_list = self.cursor.fetchall()
        profit_rate_list = []
        avg_kd_list = []
        for mdl_macd_gold_cross in mdl_macd_gold_cross_list:
            self.cursor.execute(
                "select (t.k+t.d)/2 from stock_week t "
                "where to_date('" + mdl_macd_gold_cross[4].strftime(
                    "%Y-%m-%d") + "','yyyy-mm-dd') between t.begin_date and t.end_date "
                                  "and t.code_='" + mdl_macd_gold_cross[1] + "'")
            stock_week_avg_kd = self.cursor.fetchone()
            profit_rate_list.append(mdl_macd_gold_cross[9])
            avg_kd_list.append(stock_week_avg_kd[0])

        self.oracle_manager.cursor_close()
        self.oracle_manager.connect_close()

        PictureUtil.scatter(profit_rate_list, avg_kd_list, 1.0 * (array(profit_rate_list) + 2), 15.0 * (array(profit_rate_list) + 2))
